
var app = require('../../server/server');
module.exports = function(Gpsinfo) {

	Gpsinfo.getNearlyTen = function (lat, lng, cb) {
		var now = new Date();
		now.setMinutes(now.getMinutes() - 5);
    var option = {
      where: {
        and: [
          {REPORT_TIME: {gt: now}},
        ]
      },
      order: 'REPORT_TIME desc'
    };
    var result = [];
    Gpsinfo.find(option, function (err, data) {
    	var ids = [];
      for(var i = 0; i < data.length; i++) {
      	if(ids.indexOf(data[i].USER_ID) < 0) {
      		ids.push(data[i].USER_ID);
	        result.push({
	          type: 'police',
	          msg: data[i].USER_ID,
	          addr: '(' + data[i].LATITUDE + ', ' + data[i].LONGITUDE + ')',
	          lat: data[i].LATITUDE - 0,
	          lng: data[i].LONGITUDE - 0,
	          time: data[i].REPORT_TIME,
	          distance: Math.floor(Math.abs(data[i].LATITUDE - lat) * 110000 
	            + Math.abs(data[i].LONGITUDE - lng) * 94000)
	        })
	      }
      }
      cb(null, result);
    })
  };

  Gpsinfo.remoteMethod(
    'getNearlyTen', {
      http: {path: '/getNearlyTen', verb: 'post'},
      accepts: [
        {arg: 'lat', type: 'number', required: 'true'},
        {arg: 'lng', type: 'number', required: 'true'}
      ],
      returns: {type: 'array', root: true}
    }
  );

  Gpsinfo.searchData = function (searchText, lat, lng, cb) {
    var option = {
      where: {
        or: [
          {USER_ID: {like: '%' + searchText + '%'}},
        ]
      }
    };
    var result = [];
    Gpsinfo.find(option, function (err, data) {
      var ids = [];
      for(var i = 0; i < data.length; i++) {
        if(ids.indexOf(data[i].USER_ID) < 0) {
          ids.push(data[i].USER_ID);
          result.push({
            type: 'police',
            msg: data[i].USER_ID,
            addr: '(' + data[i].LATITUDE + ', ' + data[i].LONGITUDE + ')',
            lat: data[i].LATITUDE - 0,
            lng: data[i].LONGITUDE - 0,
            time: data[i].REPORT_TIME,
            distance: Math.floor(Math.abs(data[i].LATITUDE - lat) * 110000 
              + Math.abs(data[i].LONGITUDE - lng) * 94000)
          })
        }
      }
      cb(null, result);
    })
  };

  Gpsinfo.remoteMethod(
    'searchData', {
      http: {path: '/searchData', verb: 'post'},
      accepts: [
        {arg: 'searchText', type: 'string', required: 'true'},
        {arg: 'lat', type: 'number', required: 'true'},
        {arg: 'lng', type: 'number', required: 'true'}
      ],
      returns: {type: 'array', root: true}
    }
  );

};
